package com.carpo.info.quartz;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.carpo.info.Producer;
import com.carpo.info.model.LazyStatus;
import com.carpo.info.model.PublishStatus;
import com.carpo.info.model.TInfos;
import com.carpo.info.service.IBaseInfoService;
import com.carpo.info.util.ServiceUtil;

/**
 * 
 * 定时任务类
 *
 */
public class QuartzTaskJob {

	private static final Logger logger = LoggerFactory.getLogger(QuartzTaskJob.class);
	
	public void execute(){
		logger.info("......quartz task job......");
		List<TInfos> list = new ArrayList<TInfos>();
		Map<String, IBaseInfoService> map = ServiceUtil.getServiceByType(IBaseInfoService.class);
		if(null != map){
			for(IBaseInfoService ser : map.values()){
				List<TInfos> tempList = ser.getTInfosByStatusAndLazy(PublishStatus.WAIT, LazyStatus.YES);
				if(null != tempList){
					list.addAll(tempList);
				}
			}
		}
		for(TInfos info : list){
			IBaseInfoService baseService = ServiceUtil.getServiceByTypeAndName(IBaseInfoService.class
					, info.getPlatForm());
			info.setPublishStatus(PublishStatus.DOING);
			baseService.updateTInfos(info);
			logger.info("......processing");
			String result = "";
			if(baseService.publishTInfos(info)){
				info.setPublishStatus(PublishStatus.SUCCESS);
				result = "success";
			}else{
				//非延迟消息如发布失败,则降为延迟消息再次发送
				info.setPublishStatus(PublishStatus.FAIL);
				int count = info.getFailCount();
				count ++;
				info.setFailCount(count);
				result = "fail";
			}
			info.setPublishDate(new Date());
			baseService.updateTInfos(info);
			logger.info("......prosess complete : " + result + ", itemId : " + info.getItemId());
		}
	}
}